package cn.yoaket.util;

import cn.yoaket.exception.ContextException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Alex
 */
public class MiniApplicationContext {

    private final Map<String,Object> beans = new HashMap<>();

    public MiniApplicationContext(String path){
        try {
            List<BeanDefinition> defs = XmlParse.phrase(path);
            for(var def: defs){
                beans.put(def.id, BeanGenerate.generate(def));
            }
        }catch (ContextException e){
            e.printStackTrace();
        }

    }

    public Object getBean(String id){
        Object obj = beans.get(id);
        return obj;
    }

    //通过类型来返回bean
    <T> T getBean(String id, Class<T> requiredType){
        Object bean = beans.get(id);
        if (requiredType.isInstance(bean)) {
            return (T) bean;
        }
        return null;
    }



}
